<?php
namespace Home\Model;
use Think\Model;

/**
* 
*/
class PointsLogModel extends Model
{
    /*
    $t_id 分享类型 1:分享amall优惠活动 2:分享二维码 3:扫一扫小票 4:兑换礼券
    $user_id 用户id
    $type 1加 -1减
    $log_text 备注 //分享amall优惠 等
    */
    function change_points($t_id = 0, $user_id = 0, $type = 0, $log_text = '')
    {
        //查询设置的积分
        $stype = D('ShareType');
        $t_points = intval($stype->where('t_id='.$t_id)->getField('t_points'));

        //更新会员积分
        $user = D('Users');
        $user_points = intval($user->where('user_id='.$user_id)->getField('user_points'));
        if($type == 1)
        {
            $data['user_points'] = $user_points + $t_points;
            $log['user_points']   = '+'.$t_points;
        }
        else
        {
            $data['user_points'] = $user_points - $t_points;
            $log['user_points']   = '-'.$t_points;
        }
        $user->where('user_id='.$user_id)->save($data);

        //添加积分记录
        $log['user_id']       = $user_id;

        $log['log_time']      = time();
        $log['log_text']      = $log_text;
        $log['t_id']          = $t_id;
        $log_id = $this->add($log);
        return $log_id;
    }

    function points_list($user_id,$p = 1)
    {
        $res = array();
        $count             = $this->where('user_id='.$user_id)->count();// 查询满足要求的总记录数
        $Page              = new \Think\Page($count,3);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $res['show']       = $Page->show();// 分页显示输出
        // $Page->firstRow 起始条数 $Page->listRows 获取多少条
        $res['polst']      = $this->field('*')
                           ->where('user_id='.$user_id)
                           ->order('log_id asc')
                           //->limit($Page->firstRow.','.$Page->listRows)
                           ->page($p,3)
                           ->select();
        return $res;
    }

    //比如积分抽奖
    function other_change($t_id = 0, $user_id = 0, $log_text = '', $points = 0)
    {
        //更新会员积分
        $user = D('Users');
        $user_points = intval($user->where('user_id='.$user_id)->getField('user_points'));

        $data['user_points'] = $user_points - $points;
        $user->where('user_id='.$user_id)->save($data);

        //添加积分记录
        $log['user_id']       = $user_id;
        $log['user_points']   = '-'.$points;
        $log['log_time']      = time();
        $log['log_text']      = $log_text;
        $log['t_id']          = $t_id;
        $log_id = $this->add($log);
        return $log_id;
    }
}